import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { aiApi } from "@/api/aiApi";
import type { SendChatMessageRequest, ChunkChatCompletionResponse } from "@/api/aiApi";
import questionsData from "@/assets/json/questions.json";

// 消息总是成对出现，一个用户消息，一个AI消息
type Message = {
    id: string;
    query: string;
    answer: string;
}


type Conversation = {
    id: string;
    name?: string;
    history: Message[];
}
//基本对话流
export const useDialogConversationStore = defineStore("dialogConversation", () => {
    
    const conversationList = ref<Conversation[]>([]);
    const currentConversationId = ref<string>('');
    const currentConversationIndex = ref<number>(-1);
    const generating = ref<boolean>(false);
    const internet = ref<boolean>(false);
    // 从 JSON 文件读取问题列表
    const guideQuestions = ref<string[]>(questionsData.questions);
    const interestQuestions = ref<string[]>(questionsData.questions);

    const currentConversation = computed(() => {
        if (currentConversationIndex.value === -1 || currentConversationIndex.value >= conversationList.value.length) {
            return null;
        }
        return conversationList.value[currentConversationIndex.value];
    });

    const newDialogConversationStream = async (
        userId: string,
        query: string,
        onMessage?: (data: ChunkChatCompletionResponse) => void,
        onError?: (error: Error) => void,
        onEnd?: () => void
    ) => {
        // 设置生成状态为 true
        generating.value = true;

        const apiKey = import.meta.env.VITE_AI_CHAT_ACCESS_KEY as string;
        const params: SendChatMessageRequest = {
            api_key: apiKey,
            user: userId,
            query: query,
            response_mode: 'streaming',
            inputs: {},
        };

        let conversationIdSet = false; // 标记是否已经设置过 conversation_id
        let messageCreated = false; // 标记是否已经创建过消息对象
        
        // 包装 onMessage 回调，在其中处理 conversation_id 的逻辑
        const wrappedOnMessage = (data: ChunkChatCompletionResponse) => {
            // 检查事件是否包含 conversation_id
            if ('conversation_id' in data && data.conversation_id && !conversationIdSet) {
                const convId = data.conversation_id;
                
                // 设置当前对话 ID
                currentConversationId.value = convId;
                
                // 查找是否已存在该对话
                const existingIndex = conversationList.value.findIndex(conv => conv.id === convId);
                
                if (existingIndex === -1) {
                    // 不存在，新增对话
                    addConversation(convId, [], query);
                    // 新建对话后立即保存本地
                    saveConversationLocal();
                    // 新增的对话在列表开头，所以 index 是 0
                    currentConversationIndex.value = 0;
                } else {
                    // 已存在，直接设置 index
                    currentConversationIndex.value = existingIndex;
                }
                
                conversationIdSet = true;
            }
            
            // 处理消息数据（仅针对 message 事件）
            if (data.event === 'message' && 'message_id' in data && data.message_id) {
                const conversation = conversationList.value[currentConversationIndex.value];
                
                if (conversation) {
                    // 第一次收到消息时，创建消息对象
                    if (!messageCreated) {
                        const newMessage: Message = {
                            id: data.message_id,
                            query: query,
                            answer: data.answer || "",
                        };
                        conversation.history.unshift(newMessage);
                        // 若对话名称未设置，用首条query作为名称
                        if (!conversation.name) {
                            conversation.name = query;
                        }
                        messageCreated = true;
                    } else {
                        // 后续只更新 answer 字段
                        const firstMessage = conversation.history[0];
                        if (firstMessage && firstMessage.id === data.message_id) {
                            firstMessage.answer += data.answer || "";
                        }
                    }
                }
            }
            
            // 调用原始的 onMessage 回调
            onMessage?.(data);
        };

        // 包装 onError 回调，在错误时也设置 generating 为 false
        const wrappedOnError = (error: Error) => {
            generating.value = false;
            onError?.(error);
        };

        // 包装 onEnd 回调，在结束时设置 generating 为 false
        const wrappedOnEnd = () => {
            onEnd?.();
            generating.value = false;
        };

        return await aiApi.sendChatMessageStream(params, wrappedOnMessage, wrappedOnError, wrappedOnEnd);
    }

    const sendDialogConversationStream = async (
        userId: string,
        conversationId: string,
        query: string,
        onMessage?: (data: ChunkChatCompletionResponse) => void,
        onError?: (error: Error) => void,
        onEnd?: () => void
    ) => {
        // 检查对话是否存在
        const existingIndex = conversationList.value.findIndex(conv => conv.id === conversationId);
        
        if (existingIndex === -1) {
            // 对话不存在，直接 reject
            return Promise.reject(new Error(`对话 ID ${conversationId} 不存在`));
        }

        // 设置生成状态为 true
        generating.value = true;

        const apiKey = import.meta.env.VITE_AI_CHAT_ACCESS_KEY as string;
        const params: SendChatMessageRequest = {
            api_key: apiKey,
            user: userId,
            query: query,
            response_mode: 'streaming',
            inputs: {},
            conversation_id: conversationId, // 传入对话 ID
        };

        // 在调用前设置当前对话 ID 和索引
        currentConversationId.value = conversationId;
        currentConversationIndex.value = existingIndex;

        let messageCreated = false; // 标记是否已经创建过消息对象
        
        // 包装 onMessage 回调，在其中处理消息的逻辑
        const wrappedOnMessage = (data: ChunkChatCompletionResponse) => {
            // 处理消息数据（仅针对 message 事件）
            if (data.event === 'message' && 'message_id' in data && data.message_id) {
                const conversation = conversationList.value[currentConversationIndex.value];
                
                if (conversation) {
                    // 第一次收到消息时，创建消息对象
                    if (!messageCreated) {
                        const newMessage: Message = {
                            id: data.message_id,
                            query: query,
                            answer: data.answer || "",
                        };
                        conversation.history.unshift(newMessage);
                        if (!conversation.name) {
                            conversation.name = query;
                        }
                        messageCreated = true;
                    } else {
                        // 后续只更新 answer 字段
                        const firstMessage = conversation.history[0];
                        if (firstMessage && firstMessage.id === data.message_id) {
                            firstMessage.answer += data.answer || "";
                        }
                    }
                }
            }
            
            // 调用原始的 onMessage 回调
            onMessage?.(data);
        };

        // 包装 onError 回调，在错误时也设置 generating 为 false
        const wrappedOnError = (error: Error) => {
            generating.value = false;
            onError?.(error);
        };

        // 包装 onEnd 回调，在结束时设置 generating 为 false
        const wrappedOnEnd = () => {
            onEnd?.();
            generating.value = false;
        };

        return await aiApi.sendChatMessageStream(params, wrappedOnMessage, wrappedOnError, wrappedOnEnd);
    }

    /**
     * 添加对话到列表（如果不存在）
     * @param conversationId 对话 ID
     * @param title 对话标题（可选）
     * @param createdAt 创建时间（可选，接口返回的时间戳）
     */
    const addConversation = (conversationId: string, history: Message[] = [], name?: string) => {
        // 检查 conversationList 中是否已存在该 ID
        const exists = conversationList.value.some(conv => conv.id === conversationId);
        
        if (!exists) {
            const newConversation: Conversation = {
                id: conversationId,
                name: name || '',
                history: history || [],
            };
            
            // 添加到列表开头（最新的在前面）
            conversationList.value.unshift(newConversation);
        } else {
            // console.log('对话已存在，跳过添加:', conversationId);
        }
    }

    // 将对话列表保存到本地，仅保留 id 与 name，history 统一为空数组，最多保存 20 个
    const saveConversationLocal = () => {
        const simplifiedList = conversationList.value
            .slice(-20) // 取最新的20条会话（列表中的后20条）
            .map(({ id, name }) => ({ id, name: name || '', history: [] as Message[] }));
        try {
            localStorage.setItem('dialogConversationList', JSON.stringify(simplifiedList));
        } catch (e) {
            console.error('保存对话列表到本地失败:', e);
        }
    }

    // 从本地恢复对话，仅按 id 与 name 恢复，history 为空
    const getConversationLocal = () => {
        const raw = localStorage.getItem('dialogConversationList');
        if (!raw) return;
        try {
            const list = JSON.parse(raw) as Array<{ id: string; name?: string } | null>;
            if (Array.isArray(list)) {
                list.forEach(item => {
                    if (item && typeof item.id === 'string') {
                        addConversation(item.id, [], item.name || '');
                    }
                });
            }
        } catch (e) {
            console.error('读取本地对话列表失败:', e);
        }
    }

    /**
     * 获取会话历史消息并更新本地存储
     * @param conversationId 会话 ID
     * @param userId 用户 ID
     * @returns Promise<void>
     */
    const getConversation = async (conversationId: string, userId: string): Promise<void> => {
        try {
            const apiKey = import.meta.env.VITE_AI_CHAT_ACCESS_KEY as string;
            const params = {
                api_key: apiKey,
                conversation_id: conversationId,
                user: userId,
                limit: 20 // 默认获取20条消息
            };

            const response = await aiApi.getMessages(params);
            
            // 查找对应的对话
            const conversationIndex = conversationList.value.findIndex(conv => conv.id === conversationId);
            
            if (conversationIndex !== -1) {
                const conversation = conversationList.value[conversationIndex];
                if (conversation) {
                    // 清空现有历史
                    conversation.history.length = 0;
                    
                    // 将API返回的消息转换为本地Message格式并添加到history中
                    // 注意：API返回的消息是倒序的，需要反转以保持正确的顺序
                    const messages: Message[] = response.data
                        .reverse() // 反转顺序，让最新的消息在最后
                        .map(msg => ({
                            id: msg.id,
                            query: msg.query || '',
                            answer: msg.answer || ''
                        }));
                    
                    conversation.history = messages;
                    
                    console.log(`成功获取会话 ${conversationId} 的历史消息，共 ${messages.length} 条`);
                }
            } else {
                console.warn(`未找到会话 ID: ${conversationId}`);
            }
        } catch (error) {
            console.error('获取会话历史消息失败:', error);
            throw error;
        }
    }

    
    return {
        conversationList,
        currentConversationId,
        currentConversationIndex,
        currentConversation,
        generating,
        internet,
        guideQuestions,
        interestQuestions,
        newDialogConversationStream,
        sendDialogConversationStream,
        addConversation,
        saveConversationLocal,
        getConversationLocal,
        getConversation,
    };
});
